import {constantRoutes} from "@/router/index";
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView';
import menu from "@/api/menuManagement/index";
import store from "../index";
import { handleTree } from "@/utils/common";
import { isExternal } from "@/utils/validate";
/**
 * 前端控制路由（权限筛选）
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

/**
 * 前端控制路由（递归）
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];
  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });
  return res;
}

// 后端动态路由
function dataArrayToRoutes(data) {
  const res = [];
  data.forEach(item => {
    const tmp = { ...item };
    if (tmp.component === "layout") {
      tmp.component = () => import("@/layout");
    } else {
      let path = tmp.component;
      tmp.component = resolve => require([`@/views/${path}`], resolve);
    }
    if (tmp.children) {
      tmp.children = dataArrayToRoutes(tmp.children);
    }
    res.push(tmp);
  });
  return res;
}

const state = {
  routes: [],
  addRoutes: [],
  sidebarRoutes:[],
  sidebarTitle:"",
  menuData:[],
  menus: [],
};

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = routes;
  },
  SET_WEBROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = routes;
    console.log("-----------------state.routes",state.routes)
  },
  SET_MENUDATA: (state, menuData) => {
    state.menuData = menuData;
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_SIDEBAR_ROUTES: (state, routes) => {
    state.sidebarRoutes = routes;
  },
  SET_SIDEBAR_TITLE: (state, sidebarTitle) => {
    state.sidebarTitle = sidebarTitle;
  }
};
//接口给的数据太乱，二次解析一下
function resetRouterData(arr) {
  let list = []
  arr.forEach(item =>{
    let obj = {}
    obj.component = item.component;
    obj.id = item.id;
    obj.path = isExternal(item.web_path)?item.web_path:item.web_path;
    obj.parentId = item.parent;
    obj.name = item.name;
    obj.hidden = !item.visible
    obj.meta = {title:item.name,icon:item.icon,show:!obj.hidden};
    obj.menuPermission = item.menuPermission
    obj.is_link=item.is_link
    list.push(obj)
  })
return list
}
const actions = {
  receptionRoutes({ commit }, roles) {
    return new Promise(resolve => {
      menu.getWebRouter({is_mobile:0}).then(res=>{
        let rdata = resetRouterData(res.data)
        commit("SET_MENUDATA", res.data);
        let menuList = handleTree(rdata, "id","parentId");
        const accessedRoutes = filterAsyncRouter(menuList,  true)
        let allMenu = []
        constantRoutes.map(item=>{
          if(item.path==""){
            allMenu = JSON.parse(JSON.stringify( item.children)).concat(menuList)
            item.children = accessedRoutes
          }
        })
        commit('SET_WEBROUTES', allMenu)
        // commit("SET_WEBROUTES", allMenu);
         store.state.permission.menus = accessedRoutes;
        resolve(constantRoutes);
      })
    });
  },
  allRoutes({ commit }, { menus }) {
    return new Promise(resolve => {
      let accessedRoutes;
      accessedRoutes = dataArrayToRoutes(menus);
      commit("SET_ROUTES", accessedRoutes);
      resolve(accessedRoutes);
    });
  },
};
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap,  type = false) {
  if (asyncRouterMap && asyncRouterMap) {
    asyncRouterMap = filterChildren(asyncRouterMap)
  }
  return asyncRouterMap.filter(route => {
    if (route.component) {
        route.component = loadView(route.component)
    }else{
      route.component = ParentView
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
      if (el.children && el.children.length) {
          el.children.forEach(c => {
            c.path = c.is_link?c.path:el.path + '/' + c.path
            if (c.children && c.children.length) {
              if(c.component)children.push(c)
              children = children.concat(filterChildren(c.children, c))
              return
            }
            children.push(c)
          })
          return
      }
    if (lastRouter) {
      el.path = el.is_link?el.path:lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}
export const loadView = (view) => { // 路由懒加载
  //console.log(`@/views/${view}`)
  return (resolve) => require([`@/views/${view}`], resolve)
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
};
